package com.cqc.eventbus2;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class MainActivity extends Activity {

    private TextView tv;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this);//注册事件到订阅者
        btn = (Button) findViewById(R.id.btn);
        tv = (TextView) findViewById(R.id.tv);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyEvent event = new MyEvent();
                event.setType("0");
                event.setMessage("0内容");
                EventBus.getDefault().post(event);//发布事件
            }
        });
    }

    //订阅事件处理的4种方式
//    @Subscribe
//    public void onEvent(MyEvent event){
//        if (event.getType().equals("0")) {
//            tv.setText(event.getMessage());
//        }
//    }

//   @Subscribe
//    public void onEventMainThread(MyEvent event) {
//        if (event.getType().equals("0")) {
//            tv.setText(event.getMessage());
//        }
//    }
//
//    @Subscribe
//    public void onEventPostThread(MyEvent event) {
//        if (event.getType().equals("0")) {
//            tv.setText(event.getMessage());
//        }
//    }

//    @Subscribe
//    public void onEventBackgroundThread(MyEvent event){
//        if (event.getType().equals("0")) {
//            tv.setText(event.getMessage());
//        }
//    }

//    @Subscribe
//    public void onEventAsync(MyEvent event){
//        if (event.getType().equals("0")) {
//            tv.setText(event.getMessage());
//        }
//    }

    //3.0之后，不受方法名影响，但是需要用public + @Subscribe修饰
    @Subscribe
    public void abc(MyEvent event) {
        if (event.getType().equals("0")) {
            tv.setText(event.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册
        EventBus.getDefault().unregister(this);
    }
}
